package BookCreated;

import java.io.IOException;

import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Loginout.UserBean;

@WebServlet("/BookPostEdit")
public class BookPostEdit extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		UserBean UB = (UserBean) session.getAttribute("ub");

		if (UB == null) {
			response.sendRedirect("error.html");
		} else {

			response.setContentType("text/html;charset=UTF-8");
			request.setCharacterEncoding("UTF-8");

			PrintWriter w = response.getWriter();

			Books b = new Books();

			b.setBookID(request.getParameter("bookid"));
			b.setISBN(request.getParameter("ibsn"));
			b.setCALID(request.getParameter("calid"));
			b.setBOOKNAME(request.getParameter("bookname"));
			b.setLOCATION(request.getParameter("location"));
			
			int Resultcode = 0;
			try {
				if (BooksDAO.isnewbookid(b.getBookID())) {
					Resultcode = BooksDAO.CreateBook(b);
				} else {
					Resultcode = BooksDAO.UpdateBook(b);
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			BookCalnums URL = new BookCalnums();
			URL = (BookCalnums) session.getAttribute("seachbookURL");
			if (Resultcode == 1) {		
				w.print("Update is successful."
						+ "<p> <input type=\"button\" value=\"返回列表\" onclick=\"location.href='"
						+ URL.getCaldescription() + "'\";location.reload();\">");
			} else if (Resultcode == 2) {
				w.print("Update is 	fail. (IBSN重覆.)"
						+ "<p> <input type=\"button\" value=\"返回上層\" onclick=\";history.go(-1);\">");
			} else if (Resultcode == 3) {
				w.print("Update is 	fail. (IBSN沒有輸入.)"
						+ "<p> <input type=\"button\" value=\"返回上層\" onclick=\";history.go(-1);\">");
			} else if (Resultcode == 4) {
				w.print("Update is 	fail. (系統錯誤.)"
						+ "<p> <input type=\"button\" value=\"返回上層\" onclick=\";history.go(-1);\">");
			}
		}
	}
}
